/** *
Copyright (c) 2020 kedacom * OpenATC is licensed under Mulan PSL v2. * You
can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at: *
http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN 'AS IS'
BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR
PURPOSE. * See the Mulan PSL v2 for more details.
**/
<template>
  <div class="schadule-config" v-show="isConfigShow">
    <div class="header">
      <div class="title">
        {{$t('openatc.groupcontrol.schaduleConfig')}}
      </div>
      <div class="close" @click="onCloseClick"><i class="el-icon-close"></i></div>
    </div>
    <div class="params">
      <div class="param">
        <div class="label">{{$t('openatc.groupcontrol.operateType')}}：</div>
        <div class="value">
          <template>
            <el-radio v-model="item.schedule" :label="0">{{$t('openatc.groupcontrol.manual')}}</el-radio>
            <el-radio v-model="item.schedule" :label="1">{{$t('openatc.groupcontrol.auto')}}</el-radio>
          </template>
        </div>
      </div>
      <div class="param">
        <div class="label">
          {{$t('edge.date.month')}}：
        </div>
        <div class="value">
          <el-select multiple
                      style="width:100%;"
                      v-model="item.month"
                      :placeholder="$t('edge.common.select')"
                      size="medium"
                      :collapse-tags="true"
                      @change="handleMonth(item.month, index)"
                      @visible-change="initOldOptions(item.month, $event)">
            <el-option
              v-for="item in months"
              :key="item.label"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="param">
        <div class="label">{{$t('edge.date.day') }}：</div>
        <div class="value">
          <el-select multiple
                      style="width:100%;"
                      v-model="item.day"
                      :placeholder="$t('edge.common.select')"
                      size="medium"
                      :collapse-tags="true"
                      @change="handleDay(item.day, index)"
                      @visible-change="initOldOptions(item.day, $event)">
            <el-option
              v-for="item in days"
              :key="item.label"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="param">
        <div class="label">{{$t('edge.date.date') }}：</div>
        <div class="value">
          <el-select  multiple
                      style="width:100%;"
                      :collapse-tags="true"
                      v-model="item.date"
                      :placeholder="$t('edge.common.select')"
                      size="medium"
                      @change="handleDate(item.date, index)"
                      @visible-change="initOldOptions(item.date, $event)">
            <el-option
              v-for="item in dates"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="param">
        <div class="label">{{$t('openatc.greenwaveoptimize.period')}}：</div>
        <div class="value">
          <template>
            <el-time-select
              style="width:50%;"
              size="medium"
              editable
              v-model="item.starttime"
              :picker-options="{
                start: '00:00',
                step: '00:01',
                end: '23:59'
              }">
            </el-time-select>
            <el-time-select
              style="width:50%;"
              size="medium"
              editable
              v-model="item.endtime"
              :picker-options="{
                start: '00:00',
                step: '00:01',
                end: '23:59',
                minTime: item.starttime
              }">
            </el-time-select>
          </template>
        </div>
      </div>
    </div>
    <div class="btns">
      <el-button size="medium" @click="onCloseClick">
          {{ $t('openatc.button.Cancel') }}
      </el-button>
      <el-button type="primary" size="medium" @click="onSureClick">
          {{ $t('openatc.button.OK') }}
      </el-button>
    </div>
  </div>
</template>

<script>
// @ts-ignore
import { putControl } from '../../api/control'
import { getMessageByCode } from '../../utils/responseMessage'
import dateObj from '../../views/RouteOptimize/utils.js'
const { monthsModel, daysModelCh, daysModelEn, datesModel, monthsModelEn, datesModelEn } = dateObj
export default {
  name: 'Schedule',
  components: {
  },
  props: {
    route: {
      type: Object,
      default: () => {}
    },
    isConfigShow: {
      type: Boolean,
      default: () => true
    }
  },
  computed: {
  },
  watch: {
    route: {
      handler: function (val) {
        if (val) {
          if (!val || !val.devs) {
            return false
          }
          const schadule = typeof val.schedule === 'number' ? val.schedule : 0
          const value = {
            'schedule': schadule,
            'month': val.month ? val.month : this.defaultMonth,
            'day': val.day ? val.day : this.defaultDay,
            'date': val.date ? val.date : this.defaultDate,
            'starttime': val.starttime ? val.starttime : this.defaultStarttime,
            'endtime': val.endtime ? val.endtime : this.defaultEndtime
          }
          this.item = {...val, ...value}
        }
      },
      deep: true
    }
  },
  created () {
    this.resetTab()
    let lan = this.$i18n.locale
    if (lan === 'en') {
      this.days = daysModelEn
      this.dates = datesModelEn
      this.months = monthsModelEn
    }
    if (lan === 'zh') {
      this.days = daysModelCh
      this.dates = datesModel
      this.months = monthsModel
    }
  },
  data () {
    return {
      defaultDay: [],
      defaultDate: [],
      defaultMonth: [],
      defaultStarttime: '08:00',
      defaultEndtime: '09:30',
      chartData: {},
      months: monthsModel,
      days: [],
      dates: datesModel,
      item: {},
      isShow: true
    }
  },
  methods: {
    onBlur (item) {
      // console.log(item)
      // this.item.starttime = item
    },
    resetTab () {
      this.item = {
        'schedule': 0,
        'month': this.defaultMonth,
        'day': this.defaultDay,
        'date': this.defaultDate,
        'starttime': this.defaultStarttime,
        'endtime': this.defaultEndtime
      }
      this.chartData = {}
      this.route = {}
    },
    onCloseClick () {
      // this.isConfigShow = false
      this.$emit('onCloseClick')
    },
    onSureClick () {
      const allDateArr = ['All', '全选']
      const allMonthArr = [0]
      const allDayArr = [8]
      this.item.date = this.item.date.filter(item => !allDateArr.includes(item))
      this.item.month = this.item.month.filter(item => !allMonthArr.includes(item))
      this.item.day = this.item.day.filter(item => !allDayArr.includes(item))
      if (this.item.starttime && this.item.endtime) {
        const start = Number(this.item.starttime.substring(0, 2)) * 60 * 60 + Number(this.item.starttime.substring(3, 5)) * 60
        const end = Number(this.item.endtime.substring(0, 2)) * 60 * 60 + Number(this.item.endtime.substring(3, 5)) * 60
        const duration = end - start
        if (duration < 0) {
          this.$message.warning(this.$t('openatc.groupcontrol.periodError'))
          return false
        }
        for (let dev of this.item.devs) {
          if (dev.data) {
            dev.data.duration = duration
            if (dev.data.data) {
              dev.data.data.duration = duration
            }
          }
        }
      }
      this.$emit('onSaveClick', this.item)
    },
    handleMonth (val, index) {
      let allValues = []
      // 保留所有值
      for (let item of this.months) {
        allValues.push(item.value)
      }
      // 若是全部选择
      if (val.includes(0)) this.item.month = allValues
      // 取消全部选中，上次有，当前没有，表示取消全选
      if (this.oldOptions.includes(0) && !val.includes(0)) this.item.month = []
      // 点击非全部选中，需要排除全部选中，以及，当前点击的选项
      // 新老数据都有全部选中
      if (this.oldOptions.includes(0) && val.includes(0)) {
        let tempIndex = val.indexOf(0)
        val.splice(tempIndex, 1) // 排除全选选项
        this.item.month = val
      }
      // 全选未选，但是其他选项全部选上，则全选选上，上次和当前，都没有全选
      if (!this.oldOptions.includes(0) && !val.includes(0)) {
        if (val.length === allValues.length - 1) this.item.month = [0].concat(val)
      }
      this.oldOptions = this.item.month
    },
    handleDate (val, index) {
      let allValues = []
      // 保留所有值
      for (let item of this.dates) {
        allValues.push(item)
      }
      // 判断中英文
      if (this.$i18n.locale === 'en') {
        // 若是全部选择
        if (val.includes('All')) this.item.date = allValues
        // 取消全部选中，上次有，当前没有，表示取消全选
        if (this.oldOptions.includes('All') && !val.includes('All')) this.item.date = []
        // 点击非全部选中，需要排除全部选中，以及，当前点击的选项
        // 新老数据都有全部选中
        if (this.oldOptions.includes('All') && val.includes('All')) {
          let tempIndex = val.indexOf('All')
          val.splice(tempIndex, 1) // 排除全选选项
          this.item.date = val
        }
        // 全选未选，但是其他选项全部选上，则全选选上，上次和当前，都没有全选
        if (!this.oldOptions.includes('All') && !val.includes('All')) {
          if (val.length === allValues.length - 1) this.item.date = ['All'].concat(val)
        }
      } else if (this.$i18n.locale === 'zh') {
        // 若是全部选择
        if (val.includes('全选')) this.item.date = allValues
        // 取消全部选中，上次有，当前没有，表示取消全选
        if (this.oldOptions.includes('全选') && !val.includes('全选')) this.item.date = []
        // 点击非全部选中，需要排除全部选中，以及，当前点击的选项
        // 新老数据都有全部选中
        if (this.oldOptions.includes('全选') && val.includes('全选')) {
          let tempIndex = val.indexOf('全选')
          val.splice(tempIndex, 1) // 排除全选选项
          this.item.date = val
        }
        // 全选未选，但是其他选项全部选上，则全选选上，上次和当前，都没有全选
        if (!this.oldOptions.includes('全选') && !val.includes('全选')) {
          if (val.length === allValues.length - 1) this.item.date = ['全选'].concat(val)
        }
      }
      this.oldOptions = this.item.date
    },
    handleDateInit (val, status) {
      if (status) {
        this.oldOptions = val
      } else {
        this.oldOptions = []
      }
    },
    handleDay (val, index) {
      let allValues = []
      // 保留所有值
      for (let item of this.days) {
        allValues.push(item.value)
      }
      // 若是全部选择
      if (val.includes(8)) this.item.day = allValues
      // 取消全部选中，上次有，当前没有，表示取消全选
      if (this.oldOptions.includes(8) && !val.includes(8)) this.item.day = []
      // 点击非全部选中，需要排除全部选中，以及，当前点击的选项
      // 新老数据都有全部选中
      if (this.oldOptions.includes(8) && val.includes(8)) {
        let tempIndex = val.indexOf(8)
        val.splice(tempIndex, 1) // 排除全选选项
        this.item.day = val
      }
      // 全选未选，但是其他选项全部选上，则全选选上，上次和当前，都没有全选
      if (!this.oldOptions.includes(8) && !val.includes(8)) {
        if (val.length === allValues.length - 1) this.item.day = [8].concat(val)
      }
      this.oldOptions = this.item.day
    },
    initOldOptions (val, status) {
      if (status) {
        this.oldOptions = val
      } else {
        this.oldOptions = []
      }
    },
    onRecoverClick () {
      const recoverData = {
        control: 0,
        terminal: 0,
        value: 0,
        delay: 0,
        duration: 300
      }
      const reqData = {
        param: recoverData,
        agentid: this.curDevice.agentid
      }
      this.putControl(reqData)
    },
    onExecClick () {
      const spData = JSON.parse(JSON.stringify(this.curDevice.data))
      delete spData.data.iconList
      const reqData = {
        param: spData,
        agentid: this.curDevice.agentid
      }
      if (!this.curDevice.data.data.direction || this.curDevice.data.data.direction.length === 0) {
        this.$message.error(this.$t('openatccomponents.overview.directionnull'))
        return
      }
      this.putControl(reqData)
    },
    async putControl (reqData) {
      let message = ''
      let data = await putControl(reqData)
      let success = 0
      if (!data.data.success) {
        message = getMessageByCode(data.data.code, this.$i18n.locale)
      } else {
        if (data.data.data && data.data.data.data) {
          success = data.data.data.data.success
          if (success !== 0) {
            let errormsg = 'openatccomponents.overview.putTscControlError' + success
            message = errormsg
          }
        }
      }
      if (message === '') {
        this.$message.success(this.$t('openatccomponents.common.download'))
      } else {
        this.$message.success(message)
      }
      return message
    },
    handleClickCrossIcon (allChoosedDir, curClickedPhase) {
      this.curDevice.data.data.direction = allChoosedDir.direction
      this.curDevice.data.data.peddirection = allChoosedDir.peddirection
      console.log('handleClickCrossIcon', allChoosedDir, curClickedPhase)
    },
    show () {
      this.isShow = true
    }
  }
}
</script>
<style scoped></style>
